package com.zsg.androidsipphone.ui.fragment.impl;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.Message;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import com.zsg.androidsipphone.bean.Login;
import com.zsg.androidsipphone.bean.User;
import com.zsg.androidsipphone.ui.fragment.EndFragment;
import com.zsg.androidsipphone.ui.fragment.IEndFragment;
import com.zsg.androidsipphone.util.Api;
import com.zsg.androidsipphone.util.OkHttpUtil;
import com.zsg.androidsipphone.util.ThreadPoolConfig;
import okhttp3.FormBody;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

/**
 * @author zsg
 * @date 2020/9/10
 */
public class EndFragmentService extends Fragment implements IEndFragment {

    @SuppressLint("HandlerLeak")
    static Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            User user = (User) msg.obj;
            //回显用户手机号
            EndFragment.userName.setText(user.getUserPhone());
            //保持用户信息到本地
            SharedPreferences preferences = EndFragment.userName.getContext()
                    .getSharedPreferences("userInfo", Context.MODE_PRIVATE);
            preferences.edit().putString("user",user.getUserPhone())
                    .putString("sipCode", user.getSipAccount())
                    .putString("sipPass", user.getSipPassword())
                    .apply();
        }
    };


    /**
     * 登录
     *
     * @param login 登录实体类
     * @ user y用户信息实体类
     */
    @Override
    public void login(Login login) {
        ThreadPoolConfig.buildMyThreadPool().submit(() ->{
            try {
                FormBody.Builder builder = new FormBody.Builder();
                builder.add("user", login.getPhone());
                builder.add("pass", login.getPassword());
                FormBody formBody = builder.build();
                String json = OkHttpUtil.doPost(Api.LOGIN,formBody);
                JSONObject object = new JSONObject(json);
                User user = new User(
                        object.getString("username"),
                        object.getString("sipCode"),
                        object.getString("sipPass"));
                Message msg = new Message();
                msg.obj = user;
                handler.sendMessage(msg);

            } catch (IOException | JSONException e) {
                e.printStackTrace();
            }
        });
    }
}
